package com.wty;

import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.junit.Before;
import org.junit.Test;

import java.util.function.Consumer;

/**
 * @Author:wangtianyu
 * @Date：Created on 2020/5/6 0006 21:30
 */
public class MongoDriverTestWty {

    private MongoClient client;
    private MongoDatabase dataBase;
    private MongoCollection<Document> comment;

    /**
     * 连接数据库，获取集合
     */
    @Test
    public void testConnect() {
        // 连接
        MongoClient client = new MongoClient("192.168.120.208", 27017);
        // 连接数据库 database
        MongoDatabase dataBase = client.getDatabase("commentdb");
        // 获取集合 collection
        MongoCollection<Document> comment = dataBase.getCollection("comment");
        System.out.println(comment);
    }

    @Before
    public void init() {
        // 连接
        client = new MongoClient("192.168.120.208", 27017);
        // 连接数据库 database
        dataBase = client.getDatabase("commentdb");
        // 获取集合 collection
        comment = dataBase.getCollection("comment");
        System.out.println(comment);
    }

    /**
     * 查询所有
     */
    @Test
    public void findAll(){
        FindIterable<Document> documents = comment.find();
        documents.forEach((Consumer<? super Document>) document -> {
            System.out.println(document.get("_id"));
        });
    }

    /**
     * 插入
     */
    @Test
    public void insert(){
        Document document = new Document();
        document.put("_id","2");
        document.put("comtent","超好吃！");
        comment.insertOne(document);
    }

}
